<!DOCTYPE html>
<html>
<head>
<title>Click Link Task</title>
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="../core/core.css">
<!-- JS -->
<script src="../core/core.js"></script>
<script src="../core/d3.v3.min.js"></script>
<script src="../common/ui_utils.js"></script>

<style>
.alink { text-decoration: underline; color: blue; cursor: pointer; }
</style>

<script>
// since we randomly generate links, run this in a while loop
// until we produce text that definitely contains a link,
// otherwise the script will error out and fail.
var createLinks = function(div){
  var linkCreated = false;
  while(!linkCreated){
    var txt =  ui_utils.generateWords(20).split(/\s/g);
    for(var j=0;j<txt.length; j++){
      if(Math.random() < 0.2){
        txt[j] = '<span class="alink">' + txt[j] + '</span>';
        linkCreated = true;
      }
    }
  }

  div.html(txt.join(' '));
  return txt;
}

// hook handlers to all generated links
var createClickEvents = function(){
  var elements = document.getElementsByClassName('alink');
  var correctIndex = core.randi(0, elements.length);
  var correctText = elements[correctIndex].innerHTML;
  for(var i = 0, len = elements.length; i < len; i++) {
    var e = elements[i];
    if(e.innerHTML === correctText) {
      d3.select(e).on('click', function(){ core.endEpisode(1.0, true); })
    } else {
      d3.select(e).on('click', function(){ core.endEpisode(-1.0); })
    }
  }

  return correctText;
}

var genProblem = function() {
  // generate the task
  var div = d3.select('#area');
  div.html(''); // clear previous problem, if any
  var correctText = createLinks(div);

  var any = core.getOpt(core.QueryString, 'any', false); // click Any link?
  var correctText = createClickEvents();

  // generate query text in the UI
  d3.select('#query').html('Click on the link "' + correctText + '".');
}

window.onload = function() {
  core.startEpisode();
}
</script>
</head>
<body>
<div id="wrap">
  <div id="query"></div>
  <div id="area"></div>
</div>
</body>
</html>
